package org.video.mine.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.video.mine.GlobalStr;
import org.video.mine.MyPreference;
import org.video.mine.R;
import org.video.mine.adapter.LoadDetailAdapter;
import org.video.mine.adapter.LoadingDetailAdapter;
import org.video.mine.databinding.ActivityLoadDetailBinding;
import org.video.mine.entity.LoadedEntity;
import org.video.mine.entity.LoadingEntity;
import org.video.mine.entity.ProgressLoadEntity;
import org.video.mine.event.DeleteEditEvent;
import org.video.mine.event.DeleteFileEvent;
import org.video.mine.event.DownLoadOkEvent;
import org.video.mine.event.LoadErrorEvent;
import org.video.mine.event.LoadFailedEvent;
import org.video.mine.event.NotifyLoadingPos;
import org.video.mine.event.NotifyLoadingPro;
import org.video.mine.mycode.DownTask;
import org.video.mine.mycode.DownThread;
import org.video.mine.network.JsoupGet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class LoadDetailActivity extends AppCompatActivity {

    private ActivityLoadDetailBinding binding;
    private String path;
    private List<LoadedEntity> loadEntities = new ArrayList<>();
    private List<LoadedEntity> deleteLoadEntities = new ArrayList<>();
    private List<ProgressLoadEntity> loadingEntities = new ArrayList<>();
    private List<ProgressLoadEntity> deleteLoadingEntities = new ArrayList<>();
    private LoadDetailActivity context;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0:
                    if (isLoading){
                        loadingDetailAdapter.notifyDataSetChanged();
                    }else {
                        loadDetailAdapter.notifyDataSetChanged();
                    }
                    break;
                case 1:
                    int pos = (int) msg.obj;
                    loadingDetailAdapter.notifyItemChanged(pos,"button");
                    break;
                case 2:
                    int pos1 = (int) msg.obj;
                    loadingDetailAdapter.notifyItemChanged(pos1,"pro");
                    break;
                case 3:
                    int pos2 = (int) msg.obj;
                    loadingDetailAdapter.notifyItemChanged(pos2,"check");
                    break;
                case 4:
                    int pos3 = (int) msg.obj;
                    loadDetailAdapter.notifyItemChanged(pos3,"check");
                    break;
                case 5:
                    Toast.makeText(context, (CharSequence) msg.obj,Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private boolean isLoading = false;
    private LoadDetailAdapter loadDetailAdapter;
    private LoadingDetailAdapter loadingDetailAdapter;
    private MyPreference preference;
    private List<String> deleteList = new ArrayList<>();
    private String eventCancel = "-1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_load_detail);
        setContentView(binding.getRoot());
        EventBus.getDefault().register(this);

        context = this;
        initView();
        initData();
    }

    private void initView() {
        binding.rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoadDetailActivity.this.finish();
            }
        });
        binding.rlEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLoading) {
                    if (loadEntities != null && loadEntities.size() > 0) {
                        for (int i = 0; i < loadEntities.size(); i++) {
                            if (binding.rlBottom.getVisibility() == View.GONE) {
                                loadEntities.get(i).setEdit(true);
                            } else {
                                loadEntities.get(i).setEdit(false);
                            }
                        }
                    }
                }else {
                    if (loadingEntities != null && loadingEntities.size() > 0) {
                        for (int i = 0; i < loadingEntities.size(); i++) {
                            if (binding.rlBottom.getVisibility() == View.GONE) {
                                loadingEntities.get(i).setEdit(true);
                            } else {
                                loadingEntities.get(i).setEdit(false);
                            }
                        }
                    }
                }
                if (binding.rlBottom.getVisibility() == View.GONE) {
                    binding.rlBottom.setVisibility(View.VISIBLE);
                    binding.tvEdit.setText("取消");
                } else {
                    binding.rlBottom.setVisibility(View.GONE);
                    binding.tvEdit.setText("编辑");
                    deleteList.clear();
                    binding.cbChooseAll.setChecked(false);
                }
                mHandler.sendEmptyMessage(0);
            }
        });
        binding.cbChooseAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (isLoading) {
                    for (int i = 0; i < loadingEntities.size(); i++) {
                        if (b) {
                            loadingEntities.get(i).setChecked(b);
                            if (!deleteList.contains(String.valueOf(i))) {
                                deleteList.add(String.valueOf(i));
                            }
                        } else {
                            if (eventCancel.equals("-1")) {
                                loadingEntities.get(i).setChecked(b);
                            } else {
                                if (String.valueOf(i).equals(eventCancel)) {
                                    loadingEntities.get(i).setChecked(b);
                                }
                            }
                        }
                    }
                    if (!b) {
                        if (eventCancel.equals("-1")) {
                            deleteList.clear();
                        } else {
                            deleteList.remove(eventCancel);
                        }
                    }
                }else {
                    for (int i = 0; i < loadEntities.size(); i++) {
                        if (b) {
                            loadEntities.get(i).setCheck(b);
                            if (!deleteList.contains(String.valueOf(i))) {
                                deleteList.add(String.valueOf(i));
                            }
                        } else {
                            if (eventCancel.equals("-1")) {
                                loadEntities.get(i).setCheck(b);
                            } else {
                                if (String.valueOf(i).equals(eventCancel)) {
                                    loadEntities.get(i).setCheck(b);
                                }
                            }
                        }
                    }
                    if (!b) {
                        if (eventCancel.equals("-1")) {
                            deleteList.clear();
                        } else {
                            deleteList.remove(eventCancel);
                        }
                    }
                }
                mHandler.sendEmptyMessage(0);
            }
        });
        binding.tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLoading) {
                    deleteLoadingEntities.clear();
                    List<LoadingEntity> getloadingEntities = (List<LoadingEntity>) preference.getObject(MyPreference.loading, LoadingEntity.class);
                    if (loadingEntities != null && loadingEntities.size() > 0) {
                        for (String pos : deleteList) {
                            int pos1 = Integer.valueOf(pos);
                            deleteLoadingEntities.add(loadingEntities.get(pos1));
                            for (int i=0;i<getloadingEntities.size();i++){
                                LoadingEntity loadingEntity = getloadingEntities.get(i);
                                if (loadingEntities.get(pos1).getName().equals(loadingEntity.getName()) &&
                                        loadingEntities.get(pos1).getSet().equals(loadingEntity.getSet())){
                                    getloadingEntities.remove(i);
                                    break;
                                }
                            }
                        }
                        for (ProgressLoadEntity pos : deleteLoadingEntities) {
                            loadingEntities.remove(pos);
                        }
                    }
                    preference.setObject(MyPreference.loading,getloadingEntities);
                }else {
                    deleteLoadEntities.clear();
                    if (loadEntities != null && loadEntities.size() > 0) {
                        for (String pos : deleteList) {
                            int pos1 = Integer.valueOf(pos);
                            deleteLoadEntities.add(loadEntities.get(pos1));
                        }
                        for (LoadedEntity pos1:deleteLoadEntities) {
                            loadEntities.remove(pos1);
                        }
                    }
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        deleteFils();
                    }
                }).start();
                deleteList.clear();
                mHandler.sendEmptyMessage(0);
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rcyLoaded.setLayoutManager(layoutManager);
        path = getIntent().getStringExtra("path");
        isLoading = getIntent().getBooleanExtra("isLoading", false);
        if (isLoading){
            loadingDetailAdapter = new LoadingDetailAdapter(loadingEntities,context);
            binding.rcyLoaded.setAdapter(loadingDetailAdapter);
        }else {
            loadDetailAdapter = new LoadDetailAdapter(loadEntities, context);
            binding.rcyLoaded.setAdapter(loadDetailAdapter);
        }
    }

    private void deleteFils(){
        if (!isLoading){
            for (int i=0;i<deleteLoadEntities.size();i++){
                LoadedEntity loadedEntity = deleteLoadEntities.get(i);
                File file = new File(loadedEntity.getFileDir());
                if (file.exists()){
                    file.delete();
                }
            }
            deleteLoadEntities.clear();
        }else {
            for (ProgressLoadEntity loadEntity:deleteLoadingEntities){
                DownTask.stopThread(loadEntity.getName(),loadEntity.getSet());
                DownTask.removeList(loadEntity.getName(),loadEntity.getSet());
            }
            for (int i=0;i<deleteLoadingEntities.size();i++){
                ProgressLoadEntity loadedEntity = deleteLoadingEntities.get(i);
                File file = new File(GlobalStr.getSDPath(context)+loadedEntity.getName()+"/temp/"+loadedEntity.getSet());
                if (file.exists()) {
                    for (File f : file.listFiles()) {
                        f.delete();
                    }
                    file.delete();
                }
            }
            deleteLoadingEntities.clear();
        }
        EventBus.getDefault().post(new DeleteFileEvent());
    }
    private void initData() {
        if (!isLoading) {
            if (!TextUtils.isEmpty(path)) {
                File file = new File(path);
                binding.tvName.setText(file.getName());
                if (file.exists()) {
                    for (File f : file.listFiles()) {
                        if (!f.isDirectory()) {
                            LoadedEntity loadedEntity = new LoadedEntity();
                            if (f.getName().contains(GlobalStr.saveType)){
                                loadedEntity.setName(f.getName().substring(0,f.getName().indexOf(GlobalStr.saveType)));
                            }else {
                                loadedEntity.setName(f.getName());
                            }
                            long size = 0;
                            try {
                                FileInputStream fileInputStream = new FileInputStream(f);
                                size = fileInputStream.available();
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            loadedEntity.setSize(GlobalStr.formetFileSize(size));
                            loadedEntity.setFileDir(f.getAbsolutePath());
                            loadEntities.add(loadedEntity);
                        }
                    }
                    if (loadEntities.size()>0){
                        Collections.sort(loadEntities, new Comparator<LoadedEntity>() {
                            @Override
                            public int compare(LoadedEntity o1, LoadedEntity o2) {
                                if (o1.getName().compareTo(o2.getName())<0){
                                    return -1;
                                }else {
                                    return 1;
                                }
                            }
                        });
                    }
                }
            }
        }else {
            if (!TextUtils.isEmpty(path)){
                binding.tvName.setText(path.substring(path.indexOf("movieApp/")+9,path.indexOf("/temp")));
                /*File file = new File(path);
                if (file.exists()){
                    for (File f1:file.listFiles()){

                    }
                }*/
                preference = MyPreference.getInstance();
                preference.setPreference(context);
                List<LoadingEntity> getloadingEntities = (List<LoadingEntity>) preference.getObject(MyPreference.loading, LoadingEntity.class);
                if (getloadingEntities==null){
                    getloadingEntities = new ArrayList<>();
                }

                final List<DownThread> downThreadList = DownTask.downThreadList;

                final String name = binding.tvName.getText().toString();
                for (final LoadingEntity loadingEntity:getloadingEntities){
                    if (loadingEntity.getName().equals(name)){
                        final ProgressLoadEntity progressLoadEntity = new ProgressLoadEntity();
                        progressLoadEntity.setName(name);
                        File file = new File(GlobalStr.getSDPath(context)+name+"/temp/"+loadingEntity.getSet());
                        if (file.exists()){
                            progressLoadEntity.setLoadProgress(file.listFiles().length);
                        }else {
                            progressLoadEntity.setLoadProgress(0);
                        }
                        if (loadingEntity.getAllCount()==0){
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    List<List> lists = JsoupGet.getTs(loadingEntity.getUrl());
                                    if (lists.size()>1) {
                                        progressLoadEntity.setAllProgress(lists.get(1).size());
                                    }
                                    progressLoadEntity.setImgUrl(loadingEntity.getImgUrl());
                                    progressLoadEntity.setSet(loadingEntity.getSet());
                                    for (DownThread downThread:downThreadList){
                                        if (downThread.name.equals(name) && downThread.set.equals(loadingEntity.getSet())){
                                            progressLoadEntity.setLoading(downThread.isLoading);
                                        }
                                    }
                                    loadingEntities.add(progressLoadEntity);
                                    mHandler.sendEmptyMessage(0);
                                }
                            }).start();
                        }else {
                            progressLoadEntity.setAllProgress(loadingEntity.getAllCount());
                            progressLoadEntity.setImgUrl(loadingEntity.getImgUrl());
                            progressLoadEntity.setSet(loadingEntity.getSet());
                            for (DownThread downThread:downThreadList){
                                if (downThread.name.equals(name) && downThread.set.equals(loadingEntity.getSet())){
                                    progressLoadEntity.setLoading(downThread.isLoading);
                                }
                            }
                            loadingEntities.add(progressLoadEntity);
                        }
                    }
                }
            }
        }
        mHandler.sendEmptyMessage(0);
    }

    @Subscribe
    public void notifyAdapterItem(NotifyLoadingPos event){
        if (event!=null){
            List<DownThread> downThreadList = DownTask.downThreadList;
            for (DownThread downThread:downThreadList){
                if (downThread.name.equals(loadingEntities.get(event.pos).getName()) && downThread.set.equals(loadingEntities.get(event.pos).getSet())){
                    loadingEntities.get(event.pos).setLoading(downThread.isLoading);
                    break;
                }
            }
            if (mHandler!=null) {
                Message message = Message.obtain();
                message.obj = event.pos;
                message.what=1;
                mHandler.sendMessage(message);
            }
        }
    }

    @Subscribe
    public void notifyAdapterPro(NotifyLoadingPro event){
        if (event!=null){
            int pos = -1;
            for (int i=0;i<loadingEntities.size();i++){
                ProgressLoadEntity progressLoadEntity = loadingEntities.get(i);
                if (progressLoadEntity.getName().equals(event.name) && progressLoadEntity.getSet().equals(event.set)){
                    pos=i;
                    break;
                }
            }
            if (pos!=-1) {
                File file = new File(GlobalStr.getSDPath(context) + event.name + "/temp/" + event.set);
                if (file.exists()) {
                    loadingEntities.get(pos).setLoadProgress(file.listFiles().length);
                } else {
                    loadingEntities.get(pos).setLoadProgress(0);
                }
                if (mHandler!=null) {
                    Message message = Message.obtain();
                    message.obj = pos;
                    message.what=2;
                    mHandler.sendMessage(message);
                }
            }
        }
    }

    @Subscribe
    public void downOkEvent(DownLoadOkEvent event){
        if (event!=null){
            int pos = -1;
            for (int i=0;i<loadingEntities.size();i++){
                ProgressLoadEntity progressLoadEntity = loadingEntities.get(i);
                if (progressLoadEntity.getName().equals(event.name) && progressLoadEntity.getSet().equals(event.set)){
                    pos=i;
                    break;
                }
            }
            if (pos>-1) {
                loadingEntities.remove(pos);
                mHandler.sendEmptyMessage(0);
            }
        }
    }

    @Subscribe
    public void downErrorEvent(LoadErrorEvent event){
        if (event!=null){
            int pos = -1;
            for (int i=0;i<loadingEntities.size();i++){
                ProgressLoadEntity progressLoadEntity = loadingEntities.get(i);
                if (progressLoadEntity.getName().equals(event.name) && progressLoadEntity.getSet().equals(event.set)){
                    pos=i;
                    break;
                }
            }
            if (pos>-1){
                DownTask.stopThread(event.name,event.set);
                notifyAdapterItem(new NotifyLoadingPos(pos));
            }
        }
    }

    @Subscribe
    public void deleteEdit(DeleteEditEvent event){
        if (event!=null){
            if (deleteList.contains(String.valueOf(event.pos))){
                eventCancel = String.valueOf(event.pos);
                binding.cbChooseAll.setChecked(false);
                eventCancel = "-1";
                if (isLoading) {
                    loadingEntities.get(event.pos).setChecked(false);
                }else {
                    loadEntities.get(event.pos).setCheck(false);
                }
                deleteList.remove(String.valueOf(event.pos));
            }else {
                if (isLoading) {
                    loadingEntities.get(event.pos).setChecked(true);
                    if (!deleteList.contains(String.valueOf(event.pos))){
                        deleteList.add(String.valueOf(event.pos));
                    }
                    if (deleteList.size()==loadingEntities.size()){
                        binding.cbChooseAll.setChecked(true);
                    }
                }else {
                    loadEntities.get(event.pos).setCheck(true);
                    if (!deleteList.contains(String.valueOf(event.pos))){
                        deleteList.add(String.valueOf(event.pos));
                    }
                    if (deleteList.size()==loadEntities.size()){
                        binding.cbChooseAll.setChecked(true);
                    }
                }
            }
            if (mHandler!=null) {
                Message message = Message.obtain();
                message.obj = event.pos;
                if (isLoading) {
                    message.what = 3;
                }else {
                    message.what = 4;
                }
                mHandler.sendMessage(message);
            }
        }
    }

    @Subscribe
    public void loadFailed(LoadFailedEvent event){
        if (event!=null){
            Message message = Message.obtain();
            message.what = 5;
            message.obj = event.msg;
            mHandler.sendMessage(message);
//            Toast.makeText(context, event.msg,Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
